package icu.lookyousmileface.nio.basic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author shenj
 * @title: NioBufferChannelRead
 * @projectName NettyPro
 * @date 2020/11/30 18:55
 */
public class NioBufferChannelRead {

    private static final String filePath = "src/main/resources/filedata/data1.txt";

    public static void main(String[] args) {

        File file = new File(filePath);

        try {

            FileInputStream fileInputStream = new FileInputStream(file);

            FileChannel fileInputStreamChannel = fileInputStream.getChannel();
            //获取file的大小，避免浪费内存
            ByteBuffer byteDataBuffer = ByteBuffer.allocate((int) file.length());

            fileInputStreamChannel.read(byteDataBuffer);
            //byteDataBuffer.array()将byteBuffer缓冲区中的data变成数组
            System.out.println(new String(byteDataBuffer.array()));

            fileInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
